package com.ccrfid.rmc6.resource.sys;

import com.ccrfid.rmc6.appconfig.auth.Secured;
import com.ccrfid.rmc6.appconfig.exception.pojo.AppException;
import com.ccrfid.rmc6.appconfig.exception.pojo.CustomErrors;
import com.ccrfid.rmc6.entity.sys.UploadFileEntity;
import com.ccrfid.rmc6.pojo.param.PageParam;
import com.ccrfid.rmc6.repository.search.Criterion;
import com.ccrfid.rmc6.repository.search.SearchCriteria;
import com.ccrfid.rmc6.resource.auth.pojo.UserPrincipal;
import com.ccrfid.rmc6.service.sys.UploadFileService;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Path("files")
public class UploadFileResource {
    private static final Logger logger = LoggerFactory.getLogger(UploadFileResource.class);
    @Context
    private HttpServletRequest httpServletRequest;
    @Autowired
    private UploadFileService uploadFileService;

    //查询文件列表
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Page<UploadFileEntity> searchFile(@QueryParam("fileName") String fileName, @BeanParam PageParam pageParam) {
        SearchCriteria criteria = SearchCriteria.Builder.create();
        if (fileName != null) {
            criteria.add(new Criterion("fileName", Criterion.Operator.LIKE, '%' + fileName + '%'));
        }
        PageRequest pageRequest;
        if (pageParam.getOrders() != null && pageParam.getOrders().size() > 0) {
            pageRequest = PageRequest.of(pageParam.getPageNumber(), pageParam.getPageSize(), Sort.by(pageParam.getOrders()));
        } else {
            pageRequest = PageRequest.of(pageParam.getPageNumber(), pageParam.getPageSize());
        }
        Page<UploadFileEntity> page = uploadFileService.searchFile(criteria, pageRequest);
        return page;
    }

    //上传
    @Secured
    @POST
    @Path("upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_JSON)
    public UploadFileEntity uploadFile(@FormDataParam("file") final InputStream inputStream,
                                       @FormDataParam("file") final FormDataContentDisposition fd,
                                       @Context SecurityContext securityContext) throws IOException {
        String fileName = new String(fd.getFileName().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        String clientIp = httpServletRequest.getRemoteAddr();
        UserPrincipal userPrincipal = (UserPrincipal) securityContext.getUserPrincipal();
        String userAccount = userPrincipal.getUserAccount();

        return uploadFileService.uploadFile(fileName, inputStream, userAccount, clientIp);
    }

    //下载：按文件ID下载
    @GET
    @Path("{fileId:[0-9]*}/download")
    public Response downloadFile(@PathParam("fileId") Long fileId) throws AppException {
        File file = uploadFileService.downloadFile(fileId);
        String mediaType = new MimetypesFileTypeMap().getContentType(file);
        String fileName = new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);

        return Response.ok(file, mediaType)
                .header("Content-disposition", "attachment;filename=" + fileName)
                .header("Cache-Control", "no-cache")
                .header("Transfer-File-Size", file.length())
                .build();
    }

    //下载：按文件名称下载
    @GET
    @Path("{fileName:[^*|\\:\"<>?/]+\\.[^*|\\:\"<>?/\u4E00-\u9FA5]+}/download")
    //匹配文件名
    public Response downloadFile(@PathParam("fileName") String fileName) throws AppException {
        File file = uploadFileService.downloadFile(fileName);
        String mediaType = new MimetypesFileTypeMap().getContentType(file);
        String fname = new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return Response.ok(file, mediaType)
                .header("Content-disposition", "attachment;filename=" + fname)
                .header("Cache-Control", "no-cache")
                .header("Transfer-File-Size", file.length())
                .build();
    }

    //删除
    @Secured
    @DELETE
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Boolean deleteFiles(List<Long> idList) throws AppException {
        if (idList == null) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.param_is_null.getCode(), CustomErrors.param_is_null.getReason(), "");
        }
        uploadFileService.deleteFiles(idList);
        return true;
    }
}
